package cn.js189.uqc.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

@Slf4j
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
	
	private String tempBody;
	
	public MyHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
		this.tempBody = getBody(request);
		log.info("修改后的body：{}",tempBody);
		
	}
	/**
	 * 获取请求体
	 * @param request 请求
	 * @return 请求体
	 */
	private String getBody(HttpServletRequest request) {
		try {
			ServletInputStream stream = request.getInputStream();
			StringBuilder stringBuilder = new StringBuilder();
			byte[] b = new byte[1024];
			int lens = -1;
			while ((lens = stream.read(b)) > 0) {
				stringBuilder.append(new String(b, 0, lens));
			}
			return stringBuilder.toString();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 获取请求体
	 * @return 请求体
	 */
	public String getBody(String body) {
		tempBody = body;
		return tempBody;
	}
	
	/**
	 * 需要重写这个方法
	 */
	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}
	/**
	 * 需要重写这个方法
	 */
	@Override
	public ServletInputStream getInputStream() {
		// 创建字节数组输入流
		final ByteArrayInputStream bais = new ByteArrayInputStream(tempBody.getBytes(Charset.defaultCharset()));
		
		return new ServletInputStream() {
			@Override
			public boolean isFinished() {
				return false;
			}
			
			@Override
			public boolean isReady() {
				return false;
			}
			
			@Override
			public void setReadListener(ReadListener readListener) {
			
			}
			
			@Override
			public int read() {
				return bais.read();
			}
		};
	}
	
}
